/*
 * SoundEngine.cpp
 *
 *  Created on: 2011/12/30
 *      Author: nobnak
 */
// NULL
#include <linux/stddef.h>
// assert
#include <assert.h>

#include "SoundEngine.h"

SoundEngine *SoundEngine::instance = NULL;

SoundEngine::SoundEngine() {
	SLresult result;

	try {
		// create engine
		result = slCreateEngine(&engineObject, 0, NULL, 0, NULL, NULL);
		assert(SL_RESULT_SUCCESS == result);
		if (SL_RESULT_SUCCESS != result) {
			throw "Failed to create engine";
		}

		// realize the engine
		result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE);
		assert(SL_RESULT_SUCCESS == result);
		if (SL_RESULT_SUCCESS != result) {
			throw "Failed to realize engine";
		}

		// get the engine interface, which is needed in order to create other objects
		result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine);
		assert(SL_RESULT_SUCCESS == result);
		if (SL_RESULT_SUCCESS != result) {
			throw "Failed to get engine interface";
		}
	} catch(const char *e) {
		if (engineObject != NULL)
			(*engineObject)->Destroy(engineObject);
		throw e;
	}
}

SoundEngine::~SoundEngine() {
	// destroy engine object, and invalidate all associated interfaces
	if (engineObject != NULL) {
		(*engineObject)->Destroy(engineObject);
	}
}

SoundEngine* SoundEngine::get() {
	if (instance == NULL)
		instance = new SoundEngine();
	return instance;
}
void SoundEngine::shutdown() {
	if (instance != NULL) {
		delete instance;
		instance = NULL;
	}
}

Recorder* SoundEngine::makeRecorder(int nBufferSamples, int nBuffers) {
	return new Recorder(engineEngine, nBufferSamples, nBuffers);
}
